package com.hykj.coca.control;


import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.device.TagAliasResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.github.pagehelper.PageInfo;
import com.hykj.coca.config.Config;
import com.hykj.coca.model.*;
import com.hykj.coca.result.AppBack;
import com.hykj.coca.service.*;
import com.hykj.coca.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hykj.coca.utils.StringUtil.likeString;

@Controller
@RequestMapping("/admin")
public class AdminControl {
    private Logger logger = Logger.getLogger(AdminControl.class);

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MeassgeClassService meassgeClassService;

    @Autowired
    private MeassgeService meassgeService;

    @Autowired
    private MeassgeUserService meassgeUserService;

    @RequestMapping("/index.html")
    public String index() {
        return "admin/index";
    }

    @RequestMapping("/main.html")
    public String main() {
        return "admin/main";
    }

    @RequestMapping("/top.html")
    public String top() {
        return "admin/top";
    }

    @RequestMapping("/left.html")
    public String left() {
        return "admin/left";
    }

    @RequestMapping("/exit")
    public void exit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath() + "/login.html");
        return;
    }

    /**
     * 管理员列表
     *
     * @param userName
     * @param page
     * @param status
     * @param adminModel
     * @param model
     * @return
     */
    @RequestMapping("/adminlist.html")
    public String adminlist(@RequestParam(defaultValue = "") String userName,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(required = false) Integer status,
                            @SessionAttribute("adminModel") AdminModel adminModel,
                            Model model) {
        Map condition = new HashMap();
        condition.put("status", status);
        condition.put("role", "1");
        if (!StringUtil.isEmptyString(userName)) {
            condition.put("searchKey", likeString(userName));
        }

        PageInfo<AdminModel> p = adminService.getList(condition, page);
        model.addAttribute("pageInfo", p);
        model.addAttribute("userName", userName);
        model.addAttribute("status", status);
        return "admin/adminlist";
    }

    /**
     * 删除管理员
     *
     * @param ids
     * @return
     */
    @RequestMapping("/deleteAdmin")
    @ResponseBody
    public AppBack deleteAdmin(String ids) {

        String[] Ids = ids.split(",");
        for (String id : Ids) {
            Integer Id = Integer.valueOf(id);
            adminService.deleteById(Id);
        }
        return new AppBack();
    }

    /**
     * 管理员修改界面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/admin_edit.html")
    public String admin_edit(@RequestParam(required = false) Integer id,
                             Model model) {
        if (id == null) {
            model.addAttribute("model", new AdminModel());
        } else {
            model.addAttribute("model", adminService.getById(id));
        }
        return "admin/admin_edit";
    }

    /**
     * 创建管理员
     *
     * @param userName
     * @param realName
     * @param password
     * @param status
     * @return
     */
    @RequestMapping("/createAdmin")
    @ResponseBody
    public AppBack createAdmin(String userName, String realName, String password, String status) {
        HashMap condition = new HashMap();
        condition.put("userName", userName);
        AdminModel adminModelCheck = adminService.nameCheck(condition);
        if (adminModelCheck != null)
            return new AppBack(-1, "帐号已存在");
        AdminModel adminModel = new AdminModel();
        adminModel.setUserName(userName);
        adminModel.setRealname(realName);
        adminModel.setPassword(password);
        adminModel.setStatus(Integer.valueOf(status));
        adminModel.setRole(1);
        return new AppBack(adminService.create(adminModel));
    }

    /**
     * 修改管理员
     *
     * @param id
     * @param userName
     * @param realName
     * @param password
     * @param status
     * @return
     */
    @RequestMapping("/editAdmin")
    @ResponseBody
    public AppBack editAdmin(Integer id, String userName, String realName, String password, Integer status) {
        AdminModel adminModel = new AdminModel();
        adminModel.setId(id);
        adminModel.setUserName(userName);
        adminModel.setRealname(realName);
        adminModel.setPassword(password);
        adminModel.setStatus(status);
        return new AppBack(adminService.update(adminModel));
    }

    /**
     * 修改管理员密码界面
     *
     * @return
     */

    @RequestMapping("/admin_edit_pass.html")
    public String admin_edit_pass() {
        return "admin/admin_edit_pass";
    }

    AdminModel getAdmin(HttpServletRequest request) {
        Object adminModel = request.getSession().getAttribute("adminModel");
        if (adminModel == null || !(adminModel instanceof AdminModel)) {
            return null;
        }
        return (AdminModel) adminModel;

    }

    /**
     * 修改管理员密码
     *
     * @param request
     * @param oldPass
     * @param newPass
     * @return
     */
    @RequestMapping("/changePass")
    @ResponseBody
    public AppBack changePass(HttpServletRequest request,
                              @RequestParam String oldPass,
                              @RequestParam String newPass) {
        AdminModel adminModel = getAdmin(request);
        adminModel = adminService.getById(adminModel.getId());
        if (!oldPass.equals(adminModel.getPassword())) {
            return new AppBack(-1, "密码错误");
        }
        adminModel.setPassword(newPass);
        return new AppBack(adminService.update(adminModel));
    }

    /**
     * 用户列表
     *
     * @param phone
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("/userlist.html")
    public String userlist(@RequestParam(defaultValue = "") String phone,
                           @RequestParam(defaultValue = "1") Integer page,
                           Model model) {
        Map condition = new HashMap();
        if (!StringUtil.isEmptyString(phone)) {
            condition.put("searchKey", likeString(phone));
        }

        condition.put("count", 1);
        PageInfo<UserModel> p = userService.getList(condition, page);
        model.addAttribute("pageInfo", p);
        model.addAttribute("phone", phone);
        return "admin/userlist";
    }

    /**
     * 用户修改界面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/user_edit.html")
    public String user_edit(@RequestParam(required = false) Integer id,
                            Model model) {
        if (id == null) {
            model.addAttribute("model", new UserModel());
        } else {
            model.addAttribute("model", userService.getById(id));
        }
        return "admin/user_edit";
    }

    /**
     * 添加用户
     *
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping("/createUser")
    @ResponseBody
    public AppBack createUser(String phone, String password) {
        HashMap condition = new HashMap();
        condition.put("phone", phone);
        UserModel userModelCheck = userService.nameCheck(condition);
        if (userModelCheck != null)
            return new AppBack(-1, "帐号已存在");
        UserModel userModel = new UserModel();
        userModel.setPhone(phone);
        userModel.setPassword(password);
        userModel.setStatus(1);
        return new AppBack(userService.create(userModel));
    }

    /**
     * 修改用户
     *
     * @param id
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping("/editUser")
    @ResponseBody
    public AppBack editUser(Integer id, String phone, String password) {
        UserModel userModel = new UserModel();
        userModel.setId(id);
        userModel.setPhone(phone);
        userModel.setPassword(password);
        return new AppBack(userService.update(userModel));
    }

    /**
     * 删除用户
     *
     * @param ids
     * @return
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public AppBack deleteUser(String ids) {

        String[] Ids = ids.split(",");
        for (String id : Ids) {
            Integer Id = Integer.valueOf(id);
            userService.deleteById(Id);
        }
        return new AppBack();
    }

    /**
     * 订单列表
     *
     * @param phone
     * @param orderId
     * @param beginTime
     * @param endTime
     * @param status
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("/orderlist.html")
    public String orderlist(@RequestParam(defaultValue = "") String phone,
                            @RequestParam(defaultValue = "") Integer orderId,
                            @RequestParam(required = false) String beginTime,
                            @RequestParam(required = false) String endTime,
                            @RequestParam(required = false) Integer status,
                            @RequestParam(defaultValue = "1") Integer page,
                            Model model) {
        Map condition = new HashMap();
        if (!StringUtil.isEmptyString(phone)) {
            condition.put("phone", likeString(phone));
        }
        if (orderId!=null) {
            condition.put("order_id", likeString(orderId+""));
        }
        if (!StringUtil.isEmptyString(beginTime)) {
            condition.put("beginTime", beginTime);
        }
        if (!StringUtil.isEmptyString(endTime)) {
            condition.put("endTime", endTime);
        }
        if (status != null) {
            condition.put("status", status);
        }
        PageInfo<OrderModel> p = orderService.getList(condition, page);
        model.addAttribute("pageInfo", p);
        model.addAttribute("orderId", orderId);
        model.addAttribute("phone", phone);
        model.addAttribute("beginTime", beginTime);
        model.addAttribute("endTime", endTime);
        model.addAttribute("status", status);
        return "admin/orderlist";
    }

    /**
     * 删除订单
     *
     * @param ids
     * @return
     */
    @RequestMapping("/deleteOrder")
    @ResponseBody
    public AppBack deleteOrder(String ids) {

        String[] Ids = ids.split(",");
        for (String id : Ids) {
            Integer Id = Integer.valueOf(id);
            orderService.deleteById(Id);
        }
        return new AppBack();
    }

    /**
     * 推送界面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/push.html")
    public String push(@RequestParam(required = false) String id,
                       Model model) {

        HashMap map = new HashMap();
        List<MeassgeClassModel> meassgeClassList = meassgeClassService.getList(map);

        if (!StringUtil.isEmptyString(id))
            model.addAttribute("user_id", id);
        model.addAttribute("meassge_class_list", meassgeClassList);
        return "admin/push";
    }

    /**
     * 推送消息（传id单独推送  不传id广播 ）
     *
     * @param userId
     * @param meassge_classId
     * @param meassge_content
     * @param msgUrl
     * @param pushUrl
     * @return
     */
    @RequestMapping("/pushMeassge")
    @ResponseBody
    public AppBack pushMeassge(@RequestParam(required = false) String userId,
                               @RequestParam Integer meassge_classId,
                               @RequestParam String meassge_content,
                               @RequestParam(required = false) String msgUrl,
                               @RequestParam(required = false) String pushUrl) {
        MeassgeUserModel meassgeUserModel = new MeassgeUserModel();
        MeassgeModel meassgeModel = new MeassgeModel();
        meassgeModel.setMeassge_classid(meassge_classId);
        meassgeModel.setMeassge_content(meassge_content);
        meassgeModel.setMsg_url(msgUrl);
        meassgeModel.setPush_url(pushUrl);
        meassgeService.create(meassgeModel);
        meassgeUserModel.setMeassge_id(meassgeModel.getId());
        MeassgeClassModel meassgeClassModel = meassgeClassService.getById(meassge_classId);
        JPushClient jpushClient = new JPushClient(Config.MASTER_SECRET, Config.JPUSH_APP_KEY, null, ClientConfig.getInstance());
        PushPayload payload = null;
        if (!StringUtil.isEmptyString(userId)) {
            String[] Ids = userId.split(",");
            for (String id : Ids) {
                Integer user_id = Integer.valueOf(id);
//            Integer user_id = Integer.valueOf(userId);
                meassgeUserModel.setUser_id(user_id);
                meassgeUserModel.setIs_read(0);
                meassgeUserService.create(meassgeUserModel);
                UserModel userModel = userService.getById(user_id);
                String phone=userModel.getPhone();

                payload = PushPayload.newBuilder()
                        .setPlatform(Platform.all())
                        /**
                         * 单独添加用户推送
                         */
                        .setAudience(Audience.tag(phone))
                        .setNotification(
                                Notification.newBuilder().setAlert(meassge_content)
                                        .addPlatformNotification(AndroidNotification.newBuilder()
                                                .addExtra("msgUrl", msgUrl)
                                                .addExtra("target", phone)
                                                .build())
                                        .addPlatformNotification(IosNotification.newBuilder()
                                                .addExtra("msgUrl", msgUrl)
                                                .addExtra("target", phone)
                                                .build())
                                        .build()
                        )
//                    .setMessage(Message.newBuilder()
//                            .setMsgContent(meassge_content)
//                            .addExtra("msgUrl", msgUrl)
//                            .build())
                        .setOptions(Options.newBuilder()
                                .setApnsProduction(true)
                                .build())
                        .build();
                try {
                    PushResult result = jpushClient.sendPush(payload);
                    logger.info("Got result - " + result);
                } catch (APIConnectionException e) {
                    // Connection error, should retry later
                    logger.error("Connection error, should retry later", e);
                } catch (APIRequestException e) {
                    // Should review the error, and fix the request
                    logger.error("Should review the error, and fix the request", e);
                    logger.info("HTTP Status: " + e.getStatus());
                    logger.info("Error Code: " + e.getErrorCode());
                    logger.info("Error Message: " + e.getErrorMessage());
                }

            }
        } else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.all())
                    .setNotification(
                            Notification.newBuilder()
                                    .addPlatformNotification(IosNotification.newBuilder()
                                            .addExtra("msgUrl", msgUrl)
                                            .build())
                                    .addPlatformNotification(AndroidNotification.newBuilder()
                                            .addExtra("msgUrl", msgUrl)
                                            .build())
                                    .setAlert(meassge_content)
                                    .build())
//                    .setMessage(Message.newBuilder()
//                            .setMsgContent(meassge_content)
//                            .addExtra("msgUrl", msgUrl)
//                            .build())
                    .setOptions(Options.newBuilder()
                            .setApnsProduction(true)
                            .build())
                    .build();

            meassgeUserService.createAll(meassgeUserModel);
            try {
                PushResult result = jpushClient.sendPush(payload);
                logger.info("Got result - " + result);
            } catch (APIConnectionException e) {
                // Connection error, should retry later
                logger.error("Connection error, should retry later", e);
            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                logger.error("Should review the error, and fix the request", e);
                logger.info("HTTP Status: " + e.getStatus());
                logger.info("Error Code: " + e.getErrorCode());
                logger.info("Error Message: " + e.getErrorMessage());
            }

        }


        return new AppBack();
    }

    /**
     * 推送信息列表
     *
     * @param id
     * @param page
     * @param phone
     * @param model
     * @return
     */
    @RequestMapping("/meassgelist.html")
    public String meassgelist(@RequestParam(value = "id", required = false) Integer id,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "") String phone,
                              Model model) {
        HashMap condition = new HashMap();
        condition.put("user_id", id);

        if (!StringUtil.isEmptyString(phone)) {
            HashMap map = new HashMap();
            map.put("phone", phone);
            List<UserModel> userModels = userService.getList(map);
            if (userModels.size() > 0) {
                UserModel userModel = userModels.get(0);
                condition.put("user_id", userModel.getId());
                model.addAttribute("userName", userModel.getPhone());
            } else {
                UserModel user = userService.getById(id);
                model.addAttribute("userName", user.getPhone());
            }
        } else {
            UserModel user = userService.getById(id);
            model.addAttribute("userName", user.getPhone());
        }
        PageInfo<MeassgeModel> p = meassgeService.getList(condition, page);
        model.addAttribute("user_id", id);
        model.addAttribute("pageInfo", p);
        model.addAttribute("phone", phone);
        return "admin/meassgelist";
    }
}


